mkdir -p /etc/kubernetes/ssl
mkdir -p /opt/kubernetes/cfg

cat <<EOF >/opt/kubernetes/cfg/ca-config.json
{
    "signing": {
      "default": {
        "expiry": "87600h"
      },
      "profiles": {
        "kubernetes": {
          "expiry": "87600h",
          "usages": [
              "signing",
              "key encipherment",
              "server auth",
              "client auth"
          ]
        }
      }
    }
  }
EOF


cat <<EOF >/opt/kubernetes/cfg/ca-csr.json
{
    "CN": "kubernetes",
    "key": {
      "algo": "rsa",
      "size": 2048
    },
    "names": [
      {
        "C": "CN",
        "ST": "JiangSu",
        "L": "SuZhou",
        "O": "k8s",
        "OU": "System"
      }
    ],
      "ca": {
         "expiry": "87600h"
      }
  }
EOF



cat <<EOF >/opt/kubernetes/cfg/server-csr.json
{
    "CN": "kubernetes",
    "hosts": [
       "127.0.0.1",
       "apiserver.kube.cluster",
       "10.254.0.1",
       "kubernetes",
       "kubernetes.default",
      "kubernetes.default.svc",
      "kubernetes.default.svc.cluster",
      "kubernetes.default.svc.cluster.local"
    ],
    "key": {
        "algo": "rsa",
        "size": 2048
    },
    "names": [
        {
            "C": "CN",
            "ST": "JiangSu",
            "L": "SuZhou",
            "O": "k8s",
            "OU": "System"
        }
    ]
}
EOF


cat <<EOF >/opt/kubernetes/cfg/client-csr.json
{
    "CN": "system:kube-proxy",
    "hosts": [],
    "key": {
      "algo": "rsa",
      "size": 2048
    },
    "names": [
      {
        "C": "CN",
        "ST": "JiangSu",
        "L": "SuZhou",
        "O": "k8s",
        "OU": "System"
      }
    ]
  }
EOF



cat <<EOF >/opt/kubernetes/cfg/admin-csr.json
{
    "CN": "admin",
    "hosts": [],
    "key": {
      "algo": "rsa",
      "size": 2048
    },
    "names": [
      {
        "C": "CN",
        "ST": "JiangSu",
        "L": "SuZhou",
        "O": "system:masters",
        "OU": "System"
      }
    ]
  }
EOF




KUBE_CFG_DIR=/opt/kubernetes/cfg
KUBE_SSL_DIR=/etc/kubernetes/ssl

#生成ca
cfssl gencert -initca ${KUBE_CFG_DIR}/ca-csr.json | cfssljson -bare ${KUBE_SSL_DIR}/ca

#server 
#需要修改 server-csr.json 中的etcd 集群ip 以及service-cluster-ip-range 的第一个ip
cfssl gencert -ca=${KUBE_SSL_DIR}/ca.pem -ca-key=${KUBE_SSL_DIR}/ca-key.pem -config=${KUBE_CFG_DIR}/ca-config.json -profile=kubernetes ${KUBE_CFG_DIR}/server-csr.json | cfssljson -bare ${KUBE_SSL_DIR}/server

#admin
cfssl gencert -ca=${KUBE_SSL_DIR}/ca.pem -ca-key=${KUBE_SSL_DIR}/ca-key.pem -config=${KUBE_CFG_DIR}/ca-config.json -profile=kubernetes ${KUBE_CFG_DIR}/admin-csr.json | cfssljson -bare ${KUBE_SSL_DIR}/admin

#client
cfssl gencert -ca=${KUBE_SSL_DIR}/ca.pem -ca-key=${KUBE_SSL_DIR}/ca-key.pem -config=${KUBE_CFG_DIR}/ca-config.json -profile=kubernetes  ${KUBE_CFG_DIR}/client-csr.json | cfssljson -bare ${KUBE_SSL_DIR}/client

echo -e "\033[42;37m==k8s证书生成完成===============================================================================\033[0m"
